package kuzha.runtime.jadapter;

import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.script.Bindings;

import kuzha.KuzhaObject;
import kuzha.runtime.Converter;

public class FromBindingsAdapter extends AbstractMap<String, KuzhaObject> {
	private final Bindings bindings;
	
	public FromBindingsAdapter(Bindings bindings) {
		if (bindings == null)
			throw new IllegalArgumentException();
		this.bindings = bindings;
	}
	
	@Override
	public Set<Map.Entry<String, KuzhaObject>> entrySet() {
		return new AbstractSet<Map.Entry<String, KuzhaObject>>() {
			public Iterator<Map.Entry<String, KuzhaObject>> iterator() {
				final Iterator<Map.Entry<String, Object>> iter = bindings.entrySet().iterator();
				return new Iterator<Map.Entry<String, KuzhaObject>>(){
					@Override
					public boolean hasNext() {
						return iter.hasNext();
					}
					@Override
					public Map.Entry<String, KuzhaObject> next() {
						Map.Entry<String, Object> ent = iter.next();
						return new AbstractMap.SimpleImmutableEntry<String, KuzhaObject>(
								ent.getKey(),
								Converter.toKuzhaObject(ent.getValue())
							);
					}
					@Override
					public void remove() {
						iter.remove();
					}
				};
			}
			public int size() {
				return FromBindingsAdapter.this.bindings.size();
			}
		};
	}
	
	@Override
	public KuzhaObject put(String key, KuzhaObject value) {
		return Converter.toKuzhaObject(bindings.put(key, Converter.cast(Object.class, value)));
	}
}
